package cn.achao.csr.chat.server;

import cn.achao.csr.chat.service.ChatService;
import cn.achao.csr.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * @Author: achao
 **/
@Slf4j
@Component
@ServerEndpoint("/chat/socket/{userId}")
public class ChatServer {

    // 依赖注入
    public static RedisService redisService;
    public static ChatService chatService;

    @Resource
    private void setRedisService(RedisService redisService) {
        ChatServer.redisService = redisService;
    }

    @Resource
    private void setChatService(ChatService chatService) {
        ChatServer.chatService = chatService;
    }


    /***
     * websocket 建立连接
     * 1. 本地存储 userId -> session
     * 2. redis存储 userId -> ip:port(哪个服务上)
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Long userId) {
        log.info("websocket连接成功 user【{}】", userId);
        chatService.onOpen(session, userId);
    }

    /**
     * websocket 关闭连接
     * 1. 删除本地存储
     * 2. 删除redis存储
     */
    @OnClose
    public void onClose(@PathParam("userId") Long userId) {
        log.info("websocket关闭连接 user【{}】", userId);
        chatService.onClose(userId);
    }

    /**
     * 接收处理客户端发来的数据
     */
    @OnMessage
    public void onMessage(String message, @PathParam("userId") Long userId) {
        log.debug("接收处理客户端发来的数据 user【{}】 msg 【{}】", userId, message);
        chatService.onMessage(message, userId);
    }

    /**
     * 异常处理
     * @param error
     */
    @OnError
    public void onError(Throwable error) {
        log.error("webSocket发送错误 ", error);
    }

}
